package common.util;

import common.exception.CommonErrorCode;
import common.exception.DataExchangeException;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 提供针对 DataX中使用的 List 较为常见的一些封装。 比如：checkIfValueDuplicate 可以用于检查用户配置的 writer
 * 的列不能重复。makeSureNoValueDuplicate亦然，只是会严格报错。
 */
public final class ListUtil
{


    public static void makeSureNoValueDuplicate(List<String> stringList,
                                                boolean caseSensitive)
    {
        if (null == stringList || stringList.isEmpty())
        {
            throw new IllegalArgumentException("您提供的作业配置有误, List不能为空.");
        }

        if (1 == stringList.size())
        {
            return;
        } else
        {
            List<String> list = null;
            if (!caseSensitive)
            {
                list = valueToLowerCase(stringList);
            } else
            {
                list = new ArrayList<String>(stringList);
            }

            Collections.sort(list);

            for (int i = 0, size = list.size() - 1; i < size; i++)
            {
                if (list.get(i).equals(list.get(i + 1)))
                {
                    throw DataExchangeException
                            .asDataExchangeException(
                                    CommonErrorCode.CONFIG_ERROR,
                                    String.format(
                                            "您提供的作业配置信息有误, String:[%s] 不允许重复出现在列表中: [%s].",
                                            list.get(i),
                                            StringUtils.join(stringList, ",")));
                }
            }
        }
    }


    public static boolean checkIfValueSame(List<Boolean> booleanList)
    {
        if (null == booleanList || booleanList.isEmpty())
        {
            throw new IllegalArgumentException("您提供的作业配置有误, List不能为空.");
        }

        if (1 == booleanList.size())
        {
            return true;
        } else
        {
            Boolean firstValue = booleanList.get(0);
            for (int i = 1, size = booleanList.size(); i < size; i++)
            {
                if (firstValue.booleanValue() != booleanList.get(i).booleanValue())
                {
                    return false;
                }
            }
            return true;
        }
    }

    public static List<String> valueToLowerCase(List<String> stringList)
    {
        if (null == stringList || stringList.isEmpty())
        {
            throw new IllegalArgumentException("您提供的作业配置有误, List不能为空.");
        }
        List<String> list = new ArrayList<String>(stringList.size());
        for (String string : stringList)
        {
            list.add(null != string ? string.toLowerCase() : null);
        }

        return list;
    }
}
